//最后
package com.voxel.sense.infomsg.module.map.monitor.baseInfo;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupWindow;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.L;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.SizeUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.dialog.BaseDialog;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.data.bean.MakerInfoBean;
import com.voxel.sense.infomsg.interfaces.listener.onMyDialogItemClickListener;
import com.voxel.sense.infomsg.module.firm.details.FirmInfoDetailActivity;
import com.voxel.sense.infomsg.utils.MenuDataUtil;
import com.voxel.sense.infomsg.utils.marker.cluster.strategy.FirmBeanConvertStrategy;
import com.voxel.sense.infomsg.utils.marker.cluster.strategy.MissionConverStrategey;
import com.voxel.sense.infomsg.utils.marker.cluster.strategy.StaffConverStrategey;
import com.voxel.sense.infomsg.view.MenuBean;
import com.voxel.sense.infomsg.view.menu.MultipleSelectMenuDialog;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.voxel.sense.infomsg.widget.MapStaffInfoTaskWindow;
import com.voxel.sense.infomsg.widget.map.MapInfoPopWindows;
import com.voxel.sense.infomsg.widget.map.MapStaffInfoPopWindows;
import com.voxel.sense.infomsg.widget.map.adpter.MarkerInfoWinowAdapter;
import com.voxel.sense.infomsg.widget.map.utils.IMarkerManage;
import com.voxel.sense.infomsg.widget.map.utils.MarkerManageUtils;
import com.voxel.sense.infomsg.widget.map.utils.OnCtmMarkerClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.response.FirmLocationEntity;
import cyy.example.com.facotry.model.api.response.MissionLocationEntity;
import cyy.example.com.facotry.model.api.response.MyTaskListInfoEntity;
import cyy.example.com.facotry.model.api.response.StaffDetailsEntity;
import cyy.example.com.facotry.model.api.response.TaskDetailsInfoEntity;
import cyy.example.com.facotry.model.api.response.TaskInfoEntity;

/**
 * Created by chenyiyao on 2017/11/11.
 * 实时监控 模块
 */

public class MonitorMapActivity extends BViewActivity<MonitorMapContract.Presenter>
        implements MonitorMapContract.View, AMap.OnMyLocationChangeListener, AMap.OnMapClickListener {

    @BindView(R.id.map_View)
    MapView map_view; //地图
    @BindView(R.id.titlebar)
    TextTitleBar titlebar;
    @BindView(R.id.bt_people)
    ImageButton bt_people; //人员弹窗按钮
    @BindView(R.id.bt_misson)
    Button bt_misson; //任务弹窗按钮
    @BindView(R.id.bt_firm)
    ImageButton bt_firm;//企业显示按钮

    private AMap aMap;//地图操作的实例
    private MyLocationStyle myLocationStyle;//map定位的样式
    private MultipleSelectMenuDialog mPeopledialog;//人员类筛选栏
    private MultipleSelectMenuDialog mMissonListDialog;//任务类型筛选
    private MarkerInfoWinowAdapter mMapInfoWindowAdapter;//地图marker信息窗口的适配器
    private IMarkerManage mMarkerManager;//marker管理器
    private PopWindowStaffMenu mStaffMenu;//人员菜单弹窗
    private MapStaffInfoPopWindows mStaffInfoPopWindows;//自定义人员详情弹窗
    private MapInfoPopWindows mFirmWindows; //自定义公司详情弹窗

    List<FirmLocationEntity> mFirBeanlis;//公司数据清单
    Marker mCurrentClickMarker;

    private boolean isMoveMyLocation = true;//以此数据来判断是否移动到我的位置
    private boolean mIsFirmMarkVisible = true;//是否显示公司的marker
    private boolean mIsRefreshStaff = false;//标记人员位置是否已加载过
    private double mLatitude;
    private double mLongitude;
    private MapStaffInfoTaskWindow mapStaffTaskWindow;

    public static void show(Context context, List<FirmLocationEntity> entity,
                            double latitude, double longitude) {
        Intent intent = new Intent(context, MonitorMapActivity.class);
        if (entity != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(IntentConstants.OBJECT_TYPE, (ArrayList) entity);
            bundle.putDouble(IntentConstants.LATITUDE, latitude);
            bundle.putDouble(IntentConstants.LONGITUDE, longitude);
            intent.putExtras(bundle);
        }
        context.startActivity(intent);
    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_monitor_map;
    }

    @Override
    protected MonitorMapContract.Presenter initPresenter() {
        return new MonitorMapPresenter(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        map_view.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        map_view.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        map_view.onPause();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map_view.onSaveInstanceState(outState);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMarkerManager.onDestory();
        map_view.onDestroy();
        aMap = null;
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        mFirBeanlis = new ArrayList<>();
        if (bundle != null) {
            List<FirmLocationEntity> list = (List<FirmLocationEntity>) bundle.getSerializable(IntentConstants.OBJECT_TYPE);
            if (list != null && list.size() > 0) {
                mFirBeanlis.addAll(list);
            }
            mLatitude = bundle.getDouble(IntentConstants.LATITUDE, -1);
            mLongitude = bundle.getDouble(IntentConstants.LONGITUDE, -1);
        }
        return super.initArgs(bundle);
    }


    @Override
    protected void initWidget() {
        super.initWidget();
        titlebar.setTitleText("任务监控");
        if (aMap == null) {
            aMap = map_view.getMap();
            //添加入marker管理容器中
            mMarkerManager = new MarkerManageUtils(aMap);
//												if(mLatitude != -1 && mLongitude != -1 && aMap != null){
//																//移动地图中心点
//																aMap.moveCamera(CameraUpdateFactory.
//																								changeLatLng(new LatLng(mLatitude, mLongitude)));
//												}
            aMap.moveCamera(CameraUpdateFactory.
                    changeLatLng(new LatLng(23.653317, 114.665524)));
			aMap.moveCamera(CameraUpdateFactory. zoomTo(13f));
        }
    }


    @Override
    protected void initData() {
        super.initData();
        //初始化地图
        initMap();
        mStaffMenu = new PopWindowStaffMenu(this);
        //加载地图marker点坐标
        //添加公司的地理位置
        mPresenter.doLoadStaffMenuData();
        //        FirmBeanConvertStrategy strategy = new FirmBeanConvertStrategy();
        //        mMarkerManager.addMarkers(mFirBeanlis, Constants.MARKER_TYPE_FIRM, strategy);

        //        bt_firm.setSelected(true);
        bt_people.setSelected(true);

        mPresenter.getTaskList();
        mPresenter.getLoadTaskData();
        mStaffInfoPopWindows = new MapStaffInfoPopWindows(this);
        mapStaffTaskWindow = new MapStaffInfoTaskWindow(this);
        mFirmWindows = new MapInfoPopWindows(this);
    }

    @Override
    protected void initEven() {
        super.initEven();
        //dialog消失回调
        initPeopleEvent();
        initTaskEvent();


        mStaffMenu.setItemListener(new RecyclerAdapter.AdapterListenerImpl<ConditionBean>() {
            @Override
            public void onItemClick(RecyclerAdapter.ViewHolder holder, ConditionBean bean) {
                super.onItemClick(holder, bean);
                mMarkerManager.setSameIdMarkersVisible(Constants.MARKER_TYPE_PEOPLE, bean.getTipCode(), bean.isSelect());
            }
        });

        mStaffMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                L.d("-------------------窗口消失");
            }
        });
    }

    private void refreshTask() {
        List taskList = mMissonListDialog.getDataList();
//								if(taskList == null || taskList.size() < 2){
        //弹窗数据还没有加载，需要进行加载
        mMissonListDialog.setDataList(getMissionItemList());
//								}
    }

    private void initTaskEvent() {
        if (mMissonListDialog == null)
            return;

        mMissonListDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });

        mMissonListDialog.setOnItemClickListener(new onMyDialogItemClickListener() {
            @Override
            public void onItemClick(int position, MenuBean bean) {
                //                List<Marker> markers = mMarkerManager.getMarkers(Constants.MARKER_TYPE_PEOPLE);
                if (mMarkerManager == null)
                    return;
                if (position == 0) {
                    //选中全部选项
                    mMarkerManager.setSomeTypeMarkersVisible(Constants.MARKER_TYPE_TASK, bean.isSelect(), false);
                } else {

                    mMarkerManager.setSameIdMarkersVisible(Constants.MARKER_TYPE_TASK, bean.getIconResId(), bean.isSelect());
                    //                    for (Marker data : markers) {
                    //                        PeopleMarkerEntity.BodyBean object = (PeopleMarkerEntity.BodyBean) data.getObject();
                    //                        //选择不同类型，隐藏不同的数据
                    //                        String type = object.getPersonRoleId();
                    //                        if (!TextUtils.isEmpty(type) && type.equals(bean.getID())) {
                    //                            data.setVisible(bean.isSelect());
                    //                        }
                    //                    }
                }
            }
        });
    }

    /**
     * 人员类型弹窗事件初始化
     * bandwidth
     */
    private void initPeopleEvent() {
        if (mPeopledialog == null)
            return;

        mPeopledialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });

        mPeopledialog.setOnItemClickListener(new onMyDialogItemClickListener() {
            @Override
            public void onItemClick(int position, MenuBean bean) {
                //                List<Marker> markers = mMarkerManager.getMarkers(Constants.MARKER_TYPE_PEOPLE);
                if (mMarkerManager == null)
                    return;
                if (position == 0) {
                    //选中全部选项
                    mMarkerManager.setSomeTypeMarkersVisible(Constants.MARKER_TYPE_PEOPLE, bean.isSelect(), false);
                } else {
                    mMarkerManager.setSameIdMarkersVisible(Constants.MARKER_TYPE_PEOPLE, bean.getID(), bean.isSelect());
                    //                    for (Marker data : markers) {
                    //                        PeopleMarkerEntity.BodyBean object = (PeopleMarkerEntity.BodyBean) data.getObject();
                    //                        //选择不同类型，隐藏不同的数据
                    //                        String type = object.getPersonRoleId();
                    //                        if (!TextUtils.isEmpty(type) && type.equals(bean.getID())) {
                    //                            data.setVisible(bean.isSelect());
                    //                        }
                    //                    }
                }
            }
        });
    }

    /**
     * 初始化地图
     */
    private void initMap() {
        //装载地图各类型的marker点数据集
        setLocationStyle();//设置定位样式
        //初始化markerInfo窗口的样式
        initMarkerInfoWindow();
        aMap.setInfoWindowAdapter(mMapInfoWindowAdapter);
        //地图自身的定位按钮定位的回调
        aMap.setOnMyLocationChangeListener(this);
        //点击事件
        aMap.setOnMapClickListener(this);
        //点击地图上的markerInfo窗口点击事件，绑定信息窗点击事件
        aMap.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                if (marker.isInfoWindowShown()) {
                    marker.hideInfoWindow();//这个是隐藏infowindow窗口的方法
                }
            }
        });
        mMarkerManager.setMarkerClickListener(new OnCtmMarkerClickListener() {
            @Override
            public boolean onNoClusterClick(Marker marker, Object o) {
                return handleMarkerClick(marker);
            }

            @Override
            public boolean onClusterClick(Marker marker) {
                return false;
            }
        });
    }

    /**
     * 地图marker事件处理
     */
    private boolean handleMarkerClick(Marker marker) {
        //记录当前点击的marker,从网络加载完数据后，根据id对比，是否同一个marker的窗口，再进行初始化窗口数据
        //marker的title用来区别不同类型的marker，对象id区分不同的marker
        mCurrentClickMarker = marker;
        mMapInfoWindowAdapter.setCurrentClickMarker(marker);//记录到适配器中
        //显示marker的信息窗口，显示正在加载界面
        if (!NetworkUtils.isConnected()) {
            ToastUtil.showToastLong(Factory.app(), getString(R.string.network_unavailable));
            return true;
        }
        mMapInfoWindowAdapter.setLoadDataComplete(false);
//								mCurrentClickMarker.showInfoWindow();
        LatLng position = marker.getPosition();
        //将map的中心点移动到点击的marker
        aMap.moveCamera(CameraUpdateFactory.
                changeLatLng(position));
        mPresenter.doLoadMarkerInfo(marker);
        return true;
    }

    /**
     * 设置地图定位相关设置
     */
    private void setLocationStyle() {
        //设置显示定位按钮 并且可以点击
        UiSettings settings = aMap.getUiSettings();
        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(true);
        // 是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(false);
        //定位的小图标 默认是蓝点，
        myLocationStyle = new MyLocationStyle();
        //连续定位、蓝点不会移动到地图中心点，并且蓝点会跟随设备移动。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER);
        myLocationStyle.radiusFillColor(android.R.color.transparent);
        myLocationStyle.strokeColor(android.R.color.transparent);
        aMap.setMyLocationStyle(myLocationStyle);
    }

    /**
     * 地图相关的一些btn点击事件
     */
    @OnClick({R.id.bt_people, R.id.bt_firm, R.id.bt_misson})
    void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.bt_misson://任务图标按钮
                //                if (mIsFirmMarkVisible) {
                //                    ToastUtil.showToastLong(Factory.app(), "公司位置和任务位置不可同时显示");
                //                    return;
                //                }
                dialogShowOrDismiss(mMissonListDialog);
                break;
            case R.id.bt_people://人员图标按钮
                //                mStaffMenu.showAsDropDown(bt_people);
                int i = SizeUtils.dp2px(50);
                mStaffMenu.showAsDropDown(bt_firm, -i, -bt_firm.getHeight());
                break;
            case R.id.bt_firm://公司图标按钮
                //                boolean selected = !view.isSelected();
                //                view.setSelected(selected);
                //                //公司和任务的marker是互斥的，只有其中一方能显示
                //                mIsFirmMarkVisible = !mIsFirmMarkVisible;
                //                //分别显示或隐藏公司marker或任务marker
                //                mMarkerManager.setSomeTypeMarkersVisible(Constants.MARKER_TYPE_FIRM, mIsFirmMarkVisible, false);
                //                //分别显示或隐藏公司marker或任务marker
                //                mMarkerManager.setSomeTypeMarkersVisible(Constants.MARKER_TYPE_TASK, !mIsFirmMarkVisible, true);
                break;
        }
    }

    /**
     * 控制dialog 的显示和隐藏
     */
    private void dialogShowOrDismiss(BaseDialog dialog) {
        if (dialog == null) {
            return;
        }
        if (dialog.isShowing()) {
            dialog.dismiss();
        } else {
            dialog.show();
        }
    }

    /**
     * 初始化marker点击后的信息窗口
     */
    private void initMarkerInfoWindow() {
        mMapInfoWindowAdapter = new MarkerInfoWinowAdapter(this);
        mMapInfoWindowAdapter.setOnFirmWindowClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO:这里需要优化
                if (mCurrentClickMarker == null)
                    return;
                switch (view.getId()) {
                    case R.id.tv_firm_detail://公司详情
                        FirmInfoDetailActivity.show(MonitorMapActivity.this, null, mPresenter.getMarkerInfoWindowId());
                        break;
                    case R.id.tv_mission://派发任务
                        break;
                }


            }
        });
    }

    //巡查
    //获取模拟数据
    public List<MenuBean> getPeopleItemList() {
        return MenuDataUtil.getPeopleMenuBeanist();
        //        return MenuDataUtil.getMissionBeanList();
    }

    public List<MenuBean> getMissionItemList() {
        //        return MenuDataUtil.getPeopleMenuBeanist();
        return MenuDataUtil.getMissionBeanList();
    }


    //定位回调
    @Override
    public void onMyLocationChange(Location location) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        if (isMoveMyLocation && !(latitude == 0 && longitude == 0)) {
            //移动中心点到我的位置，改变标记，后面无需再移动
            isMoveMyLocation = false;
            this.mLatitude = latitude;
            this.mLongitude = longitude;
            //移动到定位的地点
            aMap.moveCamera(CameraUpdateFactory.
                    changeLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
        } else if (!(location.getLatitude() == 0 && location.getLongitude() == 0)) {
            this.mLatitude = latitude;
            this.mLongitude = longitude;
        }
    }

    //整张地图的点击事件
    @Override
    public void onMapClick(LatLng latLng) {
        if (mCurrentClickMarker != null && mCurrentClickMarker.isInfoWindowShown()) {
            mCurrentClickMarker.hideInfoWindow();
        }
        //点击外部，公司信息窗口消失并还原状态
    }

    @Subscribe
    public void onEvent(EventEntity entity) {
        switch (entity.key) {
            case EventBusConstants.APP_CONFIG_LOAD_SUCCEED:
                refreshOptionMenu();

                break;
            case EventBusConstants.MAP_OCAMERA_CHANGE_FINISH:
                break;
        }
    }

    private void refreshOptionMenu() {
        //收到配置信息加载完成的消息，改变弹窗数据
        List peopList = mPeopledialog.getDataList();
        if (peopList == null || peopList.size() < 2) {
            //由于弹窗头部手动添加了一个选中全部，所有集合小于2的时候，才是没有取到列表数据
            //弹窗数据还没有加载，需要进行加载
            mPeopledialog.setDataList(getPeopleItemList());
        }


    }


    @Override
    public AMap getaMap() {
        return aMap;
    }


    @Override
    public void onLoadStaffMenuData(List<MenuBean> datas) {
        //人员选择列表
        mPeopledialog = new MultipleSelectMenuDialog(this, datas, "人员", R.mipmap.ic_renyuan_normal,
                R.mipmap.ic_renyuan_press, true, true);
    }

    @Override
    public void onRefreshView(String taskName, String timeEnd, int taskLevelPosition, int taskTypePosition, List firm, List user, String taskContent) {
//								mapStaffTaskWindow.show(taskName, taskContent);

    }

    @Override
    public void onLoadTaskList(List<MenuBean> datas) {
        mMissonListDialog = new MultipleSelectMenuDialog(this, datas, "任务", R.mipmap.taskinfor, R.mipmap.ic_colock_details, true, true);

    }

    @Override
    public void loadDataComplete(List<MissionLocationEntity.BodyBean> data) {
        Drawable drawable = Factory.app().getResources().getDrawable(R.mipmap.ic_renyuan_press);
        MissionConverStrategey strategey = new MissionConverStrategey();
        mMarkerManager.addMarkers(data, Constants.MARKER_TYPE_TASK, drawable, strategey);
    }

    @Override
    public void onAddMarker(List datas, String type, Drawable drawable) {
        if (Constants.MARKER_TYPE_TASK.equals(type)) {
            MissionConverStrategey strategey = new MissionConverStrategey();
            strategey.setVisible(!mIsFirmMarkVisible);
            mMarkerManager.addMarkers(datas, type, drawable, strategey);
        } else if (Constants.MARKER_TYPE_PEOPLE.equals(type)) {
            StaffConverStrategey strategey = new StaffConverStrategey();
            if (mIsRefreshStaff) {
                mMarkerManager.refreshMarkers(datas, type, strategey);
            } else {
                mIsRefreshStaff = true;
                mMarkerManager.addMarkers(datas, type, drawable, strategey);
            }
        }
    }

    @Override
    public void onShowMarkerFirmInfoWindow(MakerInfoBean data) {
        //        mMapInfoWindowAdapter.setLoadDataComplete(true);
        //        mMapInfoWindowAdapter.setCurrentMarkerDetailData(data);
        //        mCurrentClickMarker.showInfoWindow();
        mFirmWindows.show(data);
    }

    //人员详情
    @Override
    public void onShowMarkerStaffInfoWindow(StaffDetailsEntity data) {
        String realname = data.getRealname();
        String name = TextUtils.isEmpty(realname) ? data.getUsername() : data.getUsername() + "(" + realname + ")";
        StaffDetailsEntity.SysUserDetailsBean sysUserDetails = data.getSysUserDetails();

        //所在岗位
        String post = "";
        if (sysUserDetails != null) {
            post = sysUserDetails.getPost();
        }
        mStaffInfoPopWindows.show(name, data.getUserType(), post, data.getEmail(), data.getPhone());
    }


    @Override
    public void onLoadMakIconFinish(Map<String, Drawable> map) {
        mMarkerManager.putDrawables(map);
    }

    @Override
    public void onRefreshViewDialog(TaskDetailsInfoEntity.TaskBaseInfoVoBean taskBaseInfoVo) {
        mapStaffTaskWindow.show(taskBaseInfoVo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == IntentConstants.TRANCE_SELECT_TASK_ACTIVITY) {
            MyTaskListInfoEntity.BodyBean.TaskInfoListBean bean =
                    (MyTaskListInfoEntity.BodyBean.TaskInfoListBean) data.getSerializableExtra(IntentConstants.OBJECT_TYPE);
            MarkerOptions draggable = new MarkerOptions().icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_RED))
                    .position(new LatLng(mLatitude, mLongitude))
                    .draggable(false);
            Marker marker = aMap.addMarker(draggable);
            marker.setObject(bean);
            marker.setTitle(IntentConstants.TASY_TYPE);
        }
    }

}